// user_announcement.js

import express from 'express';
const router = express.Router();
import { createConnectionPool } from '../../mysql/index.js';

const connection = await createConnectionPool();

router.get('/account_admin/get', async (req, res) => {
    try {
        if (!req.query.page || !req.query.pageSize) {
            res.status(500).json({ error: '分页参数不存在' });
        }
        /* 
        page 第几页
        pageSize 数量
        */
        // 从请求参数中获取分页信息
        const page = parseInt(req.query.page) || 1;
        const pageSize = parseInt(req.query.pageSize) || 10;

        // 计算偏移量
        const offset = (page - 1) * pageSize;

        // 查询总记录数
        const countQuery = 'SELECT COUNT(*) AS count FROM account_admin';
        const countResult = await connection.query(countQuery);
        const totalRecords = countResult[0][0].count;

        // 查询数据记录，包含分页
        const dataQuery = `
            SELECT id , MCHID, userName, channe1, Todaywater, Yesterdaywater, totalwater, quota, PenRestriction, success, status, remarks, createTime 
            FROM account_admin 
            LIMIT ? OFFSET ?`;
        const dataResult = await connection.query(dataQuery, [pageSize, offset]);

        // 计算总页数
        const totalPages = Math.ceil(totalRecords / pageSize);

        // 将结果发送给客户端
        res.status(200).send({
            code: 200,
            message: '获取数据成功',
            data: dataResult[0],
            pagination: {
                totalRecords: totalRecords,
                totalPages: totalPages,
                currentPage: page,
                pageSize: pageSize
            }
        });
    } catch (error) {
        console.error('Error fetching payment records:', error);
        res.status(500).json({ error: 'Failed to fetch payment records' });
    }
});



router.delete('/account_admin/delete', async (req, res) => {
    const { id } = req.query;

    try {
        // 检查参数是否提供
        if (!id) {
            return res.status(400).json({ error: 'id is required' });
        }
        // 构造 SQL 查询
        const sql = 'DELETE FROM account_admin WHERE id = ?';
        // 执行 SQL 查询
        await connection.query(sql, [id]);

        console.log('Record with businessUser_id ' + id + ' deleted successfully');
        res.status(200).json({ code: 200, message: 'Record deleted successfully' });
    } catch (error) {
        console.error('Error deleting record:', error);
        res.status(500).json({ error: 'An error occurred while deleting record' });
    }
});




export default router;
